# %%
import time
import requests
import json
import fake_useragent
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
import pygame
# %%
url = 'https://api.forchange.cn/'
headers = {'User-Agent': fake_useragent.UserAgent().random,
           'Content-Type': 'application/json',
           'Accept': 'application/json, text/plain, */*',
           'Accept-Encoding': 'gzip, deflate, br',
           'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
           'Connection': 'keep-alive',
           'Host': 'api.forchange.cn',
           'Origin': 'https://www.forc                              hange.cn',
           'Referer': 'https://www.forchange.cn/',
           'Sec-Fetch-Dest': 'empty',
           'Sec-Fetch-Mode': 'cors',
           'Sec-Fetch-Site': 'same-site',
           'X-Requested-With': 'XMLHttpRequest'}

# %%
os.chdir(os.path.dirname(os.path.abspath(__file__)))
keys = json.load(open('keys.json', 'r'))
API_KEY = keys['API_KEY']
SECRET_KEY = keys['SECRET_KEY']
url_bd = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (
    API_KEY, SECRET_KEY)
res = requests.get(url_bd).json()
token = res["access_token"]
voice_filename = 'baidu_voice.mp3'

def baidu_voice(text):
    """This function calls the Baidu Short Text Voice Synthesis API

    Parameters:
    text (string): The text you would like to generate a voice from

    Returns:
    sound (file): A file containing the generated audio
    """
    # Synthesize the speech using the Baidu Short Text Voice Synthesis API
    data = {'tex': text, 'cuid': 'Simple_PC',
            'tok': token, 'lan': 'zh', 'ctp': 1, 'sep': 15, 'pit': 5, 'vol': 10, 'per': 0}
    response = requests.post(
        'https://tsn.baidu.com/text2audio', data=data).content

    # Save the response as a file
    with open(voice_filename, 'wb') as file:
        file.write(response)

    return voice_filename


pygame.mixer.init()
engine = None
data = {'prompt': 'Human:who are you?\nJarvis:'}
prompt = ''
last_time = time.time()
while True:
    this_prompt = input('>>').strip()
    now_time = time.time()
    if now_time - last_time > 180:
        prompt = ''
    last_time = now_time
    if this_prompt == 'quit' or this_prompt == 'exit' or this_prompt == 'bye':
        break
    if this_prompt == 'clear' or this_prompt == 'cls' or this_prompt == 'clc':
        prompt = ''
        continue
    prompt_ = prompt + f'Human:{this_prompt}\nJarvis:'
    data['prompt'] = prompt_
    try:
        res = requests.post(url, headers=headers, data=json.dumps(data))
        out = res.json()['choices'][0]['text']
    except:
        print('Error')
        continue
    prompt = f'{prompt_}{out}\n'
    print(f'Jarvis:{out}')
    try:
        try:
            pygame.mixer.music.stop()
            pygame.mixer.music.unload()
        except:
            pass
        f_name = baidu_voice(out)
        pygame.mixer.music.load(f_name)
        pygame.mixer.music.play()
    except Exception:
        if not engine:
            import pyttsx3
            engine = pyttsx3.init()
            voices = engine.getProperty('voices')
            engine.setProperty('voice', voices[0].id)

        engine.say(out)
        engine.runAndWait()
    except KeyboardInterrupt:
        pass
engine.stop()
